// 9-21 表达式求值
// 直接根据表达式求值
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX 100

int rank(char a, char b)
{
    if (b == '(')
        return 1;
    if ((a == '*' || a == '/') && (b == '+' || b == '-'))
        return 1;
    return 0;
}
int fun(int a, int b, char s)
{
    switch (s)
    {
    case '+':
        return a + b;
        break;
    case '-':
        return a - b;
        break;
    case '*':
        return a * b;
        break;
    case '/':
        return a / b;
        break;
    default:
        break;
    }
}
int operation(char *s)
{
    if (!s || s[0] == '\0')
        return 0;
    char s2[MAX];
    // char *s1 = (char *)malloc(MAX);
    int s1[MAX];
    int top1 = -1, top2 = -1;
    for (int i = 0; s[i]; i++)
    {
        if (s[i] >= '0' && s[i] <= '9')
        {
            s1[++top1] = s[i] - '0';
        }
        else
        {
            // isempty
            if (top2 < 0 || s[i] == '(')
                s2[++top2] = s[i];
            else
            {
                if (s[i] == ')')
                {
                    while (top2 >= 0 && s2[top2] != '(')
                    {
                        int a = s1[top1--];
                        int b = s1[top1--];
                        s1[++top1] = fun(b, a, s2[top2--]);
                    }
                    top2--;
                }
                else
                {
                    while (top2 >= 0 && rank(s[i], s2[top2]) == 0)
                    {
                        int a = s1[top1--];
                        int b = s1[top1--];
                        s1[++top1] = fun(b, a, s2[top2--]);
                    }
                    s2[++top2] = s[i];
                }
            }
        }
    }
    while (top2 >= 0)
    {
        int a = s1[top1--];
        int b = s1[top1--];
        s1[++top1] = fun(b, a, s2[top2--]);
    }
    printf("%d ", s1[top1]);
    return s1[top1];
}

int main()
{
    /*******************code*******************/
    char *s = "1+((2+3)*4)-5";
    operation(s);
    /******************************************/
    fflush(stdin);

    printf("\n\n****************************\n");
    printf("Press Enter key to continue\n");
    getchar();
    return 0;
    /******************************************/
}
